<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\GoodsAttribute;
use Illuminate\Http\Request;
use App\Models\Good;

class GoodController extends Controller
{

    public function index(Request $request)
    {
        if(!isset($request->catid)) $request->catid = 48;
        $this->__cate_init__($request);

        $category = $this->category;
        return view('good.index', compact( 'category'));
    }

    public function list(Request $request)
    {
        $this->__cate_init__($request);
        $keyword = $request->keyword;

        if($request->catid) {
            $where = ['status' => 1,'catid'=> $request->catid];
        }else{
            $where = ['status' => 1];
        }
        if($keyword)
        {
            $model = Good::where($where)->where(function ($query) use($keyword){
                $query->orWhere('title','like', "%{$keyword}%");
                $query->orWhere('rtitle','like', "%{$keyword}%");
            });
        }else{
            $model = Good::where($where);
        }

        $order = $request->get('order', 'default');
        switch ($order)
        {
            case 'new':
                $pageList = $model->orderBy('id', 'desc')->paginate(15);
                break;
            case 'price':
                $pageList = $model->orderBy('price', 'asc')->paginate(15);
                break;
            case 'number':
                $pageList = $model->orderBy('salled_number', 'desc')->paginate(15);
                break;
            default:
                $pageList = $model->orderBy('updated_at', 'desc')->paginate(15);
                break;
        }
        //获取当前url
        $full_url = preg_replace('/&order=([\w]+)/', '', \URL::full());

        $pageList->appends(['catid'=> $request->catid]);
        $pageList->appends(['keyword'=> $request->keyword]);
        if(isset($request->jp))
        {
            $pageList->appends(['jp'=> $request->jp]);
        }
        $pageList->everypage = 15;
        $category = $this->category;
        if($request->isMethod('post')){
            $pageList['view'] = view('good.items', compact('pageList', 'category', 'keyword', 'full_url', 'order'))->render();
            return $pageList;
        }
        return view('good.list', compact('pageList', 'category', 'keyword', 'full_url', 'order'));
    }

    public function detail(Request $request)
    {
        $info = Good::findOrFail($request->id);
        if($request->isMethod('post')){

            $attr = GoodsAttribute::findOrFail($request->fid);
            return $attr;
        }
        return view('good.detail', compact('info'));
    }
}
